package com.sophialex.health.record.common.widget;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

import com.sophialex.health.record.common.Messages;
import com.sophialex.health.system.frame.resource.RcpResourceManager;
import com.sophialex.health.system.frame.widgets.treeCombo.TreeCheckUtil;

/**
 * 树下拉框控件 (带复选框和确定按钮）
 * 
 */
public class TreeCombo extends Composite {

	private Text text;
	private Button button, btnOK;
	private Point point;
	private ComboShell popup;// = new ComboShell(this.getShell());
	private Tree tree;// = popup.getTree();
	int treeStyle;
	TreeComboInit init;

	private int width = 70;
	private int hight = 200;

	private TreeItem selectedItem;

	public Tree getTree() {
		return tree;
	}

	public void setTree(Tree tree) {
		this.tree = tree;
	}

	public Point getPoint() {
		return point;
	}

	public void setPoint(Point point) {
		this.point = point;
	}

	public String getText() {
		return text.getText();
	}

	public void setText(String text) {
		this.text.setText(text);
	}

	public void setSelection(int index) {
		if (tree != null && index < tree.getItemCount() && index >= 0) {
			tree.setSelection(tree.getItem(0));
			text.setText(tree.getItem(0).getText());
			selectedItem = tree.getItem(0);
		}
	}

	/**
	 * 树节点对象的data值
	 * 
	 * @param value
	 */
	public void setSelection(Object data) {
		if (tree != null) {
			for (TreeItem it : tree.getItems()) {
				setSelection(it, data);
			}
		}
	}

	public void setSelection(TreeItem item, Object data) {
		if (item.getData().equals(data)) {
			tree.setSelection(item);
			text.setText(item.getText());
			selectedItem = item;
		} else {
			if (item.getItemCount() > 0) {
				for (TreeItem it : item.getItems()) {
					setSelection(it, data);
				}
			}
		}
	}

	/**
	 * 默认为复选样式 Create the composite
	 * 
	 * @param parent
	 * @param style
	 */
	public TreeCombo(Composite parent, TreeComboInit init) {
		super(parent, SWT.SCROLL_LINE | SWT.BORDER);
		this.treeStyle = SWT.CHECK;
		this.init = init;
		setLayout(new FormLayout());
		popup = new ComboShell(this.getShell());
		tree = popup.getTree();
		text = new Text(this, SWT.NONE);
		text.setEditable(false);
		text.setBackground(RcpResourceManager.getColor(255, 255, 255));
		final FormData fd_text = new FormData();
		fd_text.right = new FormAttachment(100, -16);
		fd_text.bottom = new FormAttachment(100);
		fd_text.top = new FormAttachment(0, 0);
		fd_text.left = new FormAttachment(0, 0);
		text.setLayoutData(fd_text);
		button = new Button(this, SWT.ARROW | SWT.DOWN);
		final FormData fd_button = new FormData();
		fd_button.bottom = new FormAttachment(text, 0, SWT.BOTTOM);
		fd_button.top = new FormAttachment(0);
		fd_button.left = new FormAttachment(text);
		fd_button.right = new FormAttachment(100);
		button.setLayoutData(fd_button);
		popup.setVisible(false);
		addListenter();
		addDisposeListener(new DisposeListener() {
			public void widgetDisposed(final DisposeEvent e) {
				popup.dispose();
				popup = null;
			}
		});
	}

	/**
	 * Create the composite
	 * 
	 * @param parent
	 * @param style
	 */
	public TreeCombo(Composite parent, int treeStyle, TreeComboInit init) {
		super(parent, SWT.SCROLL_LINE | SWT.BORDER);
		this.treeStyle = treeStyle;
		this.init = init;
		setLayout(new FormLayout());
		popup = new ComboShell(this.getShell());
		tree = popup.getTree();
		text = new Text(this, SWT.NONE);
		text.setEditable(false);
		text.setBackground(RcpResourceManager.getColor(255, 255, 255));
		final FormData fd_text = new FormData();
		fd_text.right = new FormAttachment(100, -16);
		fd_text.bottom = new FormAttachment(100);
		fd_text.top = new FormAttachment(0, 0);
		fd_text.left = new FormAttachment(0, 0);
		text.setLayoutData(fd_text);
		button = new Button(this, SWT.ARROW | SWT.DOWN);
		final FormData fd_button = new FormData();
		fd_button.bottom = new FormAttachment(text, 0, SWT.BOTTOM);
		fd_button.top = new FormAttachment(0);
		fd_button.left = new FormAttachment(text);
		fd_button.right = new FormAttachment(100);
		button.setLayoutData(fd_button);
		popup.setVisible(false);
		addListenter();
		addDisposeListener(new DisposeListener() {
			public void widgetDisposed(final DisposeEvent e) {
				popup.dispose();
				popup = null;
			}
		});
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	public void addModifyListener(ModifyListener modifyListener) {
		text.addModifyListener(modifyListener);
	}

	public void addListenter() {

		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				// popup.setParent(button.getShell());
				dropDown();
			}
		});

		btnOK.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				doWidgetSelected();
				popup.setVisible(false);
			}
		});
		tree.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				if ((treeStyle & SWT.CHECK) == 0) {
					TreeItem item = (TreeItem) e.item;
					selectedItem = item;
					text.setText(item.getText());
					text.setData(item.getData());
				}
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				popup.setVisible(false);
				if ((treeStyle & SWT.CHECK) == 0)
					TreeCheckUtil.removeAllChecked(tree);
			}

		});

		popup.addShellListener(new ShellListener() {
			public void shellActivated(ShellEvent e) {
				// TODO Auto-generated method stub

			}

			public void shellClosed(ShellEvent e) {
				// TODO Auto-generated method stub

			}

			// 没有被激活事件
			public void shellDeactivated(ShellEvent e) {
				// TODO Auto-generated method stub
				boolean flag = button.isFocusControl();
				if (!flag)
					popup.setVisible(false);
			}

			public void shellDeiconified(ShellEvent e) {
				// TODO Auto-generated method stub

			}

			public void shellIconified(ShellEvent e) {
				// TODO Auto-generated method stub

			}
		});
	}

	protected void doWidgetSelected() {
		if ((treeStyle & SWT.CHECK) == 0) {
			if (tree.getSelectionCount() > 0) {
				text.setText(tree.getSelection()[0].getText());
				text.setData(tree.getSelection()[0].getData());
			}
		} else {
			String ks = ""; //$NON-NLS-1$
			String kh = ""; //$NON-NLS-1$
			String sqlKh = ""; //$NON-NLS-1$
			if (tree.getItemCount() == 1) {
				TreeItem root = tree.getItems()[0];

				if ((treeStyle & SWT.CHECK) == 0
						&& TreeCheckUtil.hasAllCheckedItem(root)) {
					kh = ""; //$NON-NLS-1$
				} else {
					if (root.getItemCount() > 0)
						for (TreeItem item : root.getItems()) {
							if (item.getChecked()) {
								if ("".equals(ks)) { //$NON-NLS-1$
									ks = item.getText();
								} else {
									ks = ks + "," + item.getText(); //$NON-NLS-1$
								}

								if ("".equals(kh)) { //$NON-NLS-1$
									kh = item.getData().toString();
								} else {
									kh = kh + "," + item.getData().toString(); //$NON-NLS-1$
								}

								if ("".equals(sqlKh)) { //$NON-NLS-1$
									sqlKh = "'" + item.getData().toString() + "'"; //$NON-NLS-1$ //$NON-NLS-2$
								} else {
									sqlKh = sqlKh + "," + "'" //$NON-NLS-1$ //$NON-NLS-2$
											+ item.getData().toString() + "'"; //$NON-NLS-1$
								}
							}
						}
				}
			}
			text.setText(ks);
			text.setData(kh);
			text.setData("Sql", sqlKh); //$NON-NLS-1$
		}
	}

	public String getSqlText() {
		return (String) text.getData("Sql"); //$NON-NLS-1$
	}

	public Object getTreeItemData() {
		if (selectedItem != null) {
			return selectedItem.getData();
		} else
			return null;
	}

	public void dropDown() {
		if (!popup.isVisible()) {
			try {
				Rectangle r = text.getBounds();
				int y1 = r.y + r.height;
				Display display = Display.getCurrent();
				Rectangle parentRect = display.map(getParent(), null,
						getBounds());
				Point comboSize = getSize();
				Rectangle displayRect = getMonitor().getClientArea();
				int width = Math.max(comboSize.x, 10 + 2);
				int height = 5 + 2;
				int x = parentRect.x;
				int y = parentRect.y + comboSize.y;
				if (y + height > (displayRect.y + displayRect.height) / 2)
					y = parentRect.y - 200;
				if (x + width > displayRect.x + displayRect.width)
					x = displayRect.x + displayRect.width - 10;
				popup.setBounds(x, y, width + this.width, this.hight);
				popup.setVisible(true);
				popup.open();
				popup.layout();
				while (popup != null && !popup.isDisposed()) {
					if (!display.readAndDispatch())
						display.sleep();
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} else {
			popup.setVisible(false);
		}

	}

	@Override
	public Object getData() {
		return text.getData();
	};

	// 弹出的shell
	class ComboShell extends Shell {
		private Tree tree;

		/**
		 * Launch the application
		 * 
		 * @param args
		 */

		public Tree getTree() {
			return tree;
		}

		public void setTree(Tree tree) {
			this.tree = tree;
		}

		/**
		 * Create the shell
		 * 
		 * @param display
		 * @param style
		 */
		public ComboShell() {
			super(SWT.ON_TOP | SWT.TOOL);// 无提示栏
			createContents();
			setLayout(new FillLayout());
		}

		/**
		 * Create the shell
		 * 
		 * @param display
		 * @param style
		 */
		public ComboShell(Shell parent) {
			super(parent, SWT.ON_TOP | SWT.TOOL);// 无提示栏
			createContents();
			setLayout(new FillLayout());
		}

		/**
		 * Create contents of the window
		 */
		protected void createContents() {
			setSize(191, 374);
			setBackground(RcpResourceManager.getColor(240, 240, 245));
			final Composite container = new Composite(this, SWT.NONE);
			container.setBackground(RcpResourceManager.getColor(240, 240, 245));
			container.setLayout(new GridLayout());
			tree = new Tree(container, treeStyle);
			if ((treeStyle & SWT.CHECK) == 0)
				TreeCheckUtil.addCheckItemListener(tree);
			tree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
			btnOK = new Button(container, SWT.NONE);
			final GridData gd_btnOK = new GridData(SWT.CENTER, SWT.CENTER,
					false, false);
			gd_btnOK.widthHint = 57;
			btnOK.setLayoutData(gd_btnOK);
			btnOK.setText(Messages.TreeCombo_0);
			init.initTree(tree);
		}

		@Override
		protected void checkSubclass() {
		}
	}

	public void setWindthAndHight(int width, int hight) {
		this.width = width;
		this.hight = hight;
	}

}